package system

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"github.com/tencentyun/cos-go-sdk-v5"
	"net/http"
	"net/url"
	"os"
	"private-domain-overseas-service/pkg/constant"
	"strings"
	"time"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SystemUploadFileLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewSystemUploadFileLogic - 上传文件
func NewSystemUploadFileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SystemUploadFileLogic {
	return &SystemUploadFileLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SystemUploadFileLogic) SystemUploadFile(r *http.Request) (resp *types.SystemUploadFileResponse, err error) {
	err = r.ParseMultipartForm(constant.MaxFileSize)
	if err != nil {
		return nil, err
	}
	file, handler, err := r.FormFile("file")
	if err != nil {
		return nil, err
	}
	defer file.Close()
	u, _ := url.Parse(l.svcCtx.Config.Cos.Url)

	b := &cos.BaseURL{BucketURL: u}
	client := cos.NewClient(b, &http.Client{
		Timeout: 5 * time.Minute, // 设置 5 分钟超时
		Transport: &cos.AuthorizationTransport{
			// 通过环境变量获取密钥
			// 环境变量 SECRETID 表示用户的 SecretId，登录访问管理控制台查看密钥，https://console.cloud.tencent.com/cam/capi
			SecretID: os.Getenv(l.svcCtx.Config.Cos.SecretId), // 用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
			// 环境变量 SECRETKEY 表示用户的 SecretKey，登录访问管理控制台查看密钥，https://console.cloud.tencent.com/cam/capi
			SecretKey: os.Getenv(l.svcCtx.Config.Cos.SecretKey), // 用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
		},
	})

	var key string
	// 文件后缀
	ext := ""
	parts := strings.Split(handler.Filename, ".")
	if len(parts) > 1 {
		ext = parts[len(parts)-1] // 获取最后一个部分作为扩展名
	}
	var fileName string
	switch r.FormValue("type") {
	//积分商城相关图片
	case constant.IntegralGoodsImageId:
		fileName = fmt.Sprintf("%v.%s", uuid.New(), ext)
		key = constant.IntegralGoodsImage + fileName
		//海外商城图片
	case constant.MallGoodsImageId:
		fileName = fmt.Sprintf("%v.%s", uuid.New(), ext)
		key = constant.MallGoodsImage + fileName
	default:
		fileName = fmt.Sprintf("%v.%s", uuid.New(), ext)
		key = constant.HzBaySdkFilePath + fileName
	}

	// 上传
	_, err = client.Object.Put(context.Background(), key, file, nil)
	if err != nil {
		return nil, err
	}

	//返回组装数据
	return &types.SystemUploadFileResponse{
		FileName: fileName,
		Url:      key,
	}, nil
}
